package com.mrzhou.auth.support.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

/**
 * 默认当前的配置不生效;
 *  配置是否需要修改登录成功返回后的json格式
 */
@Component
@Aspect
@Slf4j
@ConditionalOnProperty(prefix = "spring.security.oauth2", name = "use-default-oauth2-translator", havingValue = "false", matchIfMissing = false)
public class AuthTokenAspect {

    /**
     * SecurityOAuth2的oauth/token接口的方法为TokenEndpoint.postAccessToken
     */
    @Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        // 放行
        ResultResponse resultResponse = new ResultResponse();
        Object proceed = pjp.proceed();
        if (proceed != null) {
            ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>)proceed;
            OAuth2AccessToken body = responseEntity.getBody();
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                resultResponse.setCode(HttpStatus.OK.value());
                resultResponse.setMsg("登录成功！");
                resultResponse.setData(body);
            } else {
                log.error("error:{}", responseEntity.getStatusCode().toString());
                resultResponse.setCode(HttpStatus.BAD_REQUEST.value());
                resultResponse.setMsg("获取授权码失败");
            }
        }
        return ResponseEntity.status(HttpStatus.OK.value()).body(resultResponse);
    }

}
